package com.zkingsoft.zkingbase.manager;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zkingsoft.zkingbase.base.ZkApplication;
import com.zkingsoft.zkingbase.bean.resp.BaseResp;
import com.zkingsoft.zkingbase.bean.resp.MapInfoBean;
import com.zkingsoft.zkingbase.bean.resp.WXPayResp;
import com.zkingsoft.zkingbase.constant.Constant;
import com.zkingsoft.zkingbase.utils.BitmapUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Created by ytf on 2016/11/15.
 * 微信工具类，除了支付，其他方法不能用
 */
public class WXManager
{

    private static WXManager mInstance;

//    private WXEntryActivity callBackTarget;
    private IWXAPI api;
    private static Context context;
    private OkHttpManager httpManager;

    private static final int THUMB_SIZE = 150;

    private WXManager(Context context)
    {
        api = ZkApplication.getAppContext().getWxApi();
        httpManager = OkHttpManager.getInstance();
    }

    public static WXManager getInstance(Context ctx)
    {
        context = ctx;
        if (mInstance == null)
        {
            synchronized (WXManager.class)
            {
                if (mInstance == null)
                {
                    mInstance = new WXManager(context);
                }
            }
        }
        return mInstance;
    }

    private String buildTransaction(final String type)
    {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /***
     * 分享文本到微信
     *
     * @param shareContent 分享内容
     * @param circleOrChat true朋友圈 false聊天会话
     */
    public void shareText(String shareContent, boolean circleOrChat)
    {
        WXTextObject tObj = new WXTextObject();
        tObj.text = shareContent;
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = tObj;
        msg.description = shareContent;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text");
        req.scene = circleOrChat ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        req.message = msg;
        api.sendReq(req);
    }

    public void shareImage(Bitmap bmp, boolean circleOrChat)
    {
        WXImageObject imgObj = new WXImageObject(bmp);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        msg.thumbData = BitmapUtils.bmpToByteArray(thumbBmp);  // 设置缩略图

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = circleOrChat ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    public void shareImage(String bmpUrl, boolean circleOrChat)
    {
        WXImageObject imgObj = new WXImageObject();
        imgObj.imagePath = bmpUrl;

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap bmp = null;
        try
        {
            bmp = BitmapFactory.decodeStream(new URL(bmpUrl).openStream());
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        msg.thumbData = BitmapUtils.bmpToByteArray(thumbBmp);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = circleOrChat ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    public void sharePage(String urlLink, String title,String des, Bitmap bmpThumb, boolean circleOrChat)
    {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = urlLink;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = des;
        msg.thumbData = BitmapUtils.bmpToByteArray(bmpThumb);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = circleOrChat ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    public void login()
    {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "123456";
        api.sendReq(req);
    }

    private Handler handler;

    /***
     * 请求服务器获得预支付订单
     * @param params 1. body 商品名称  2.total_fee  总金额  3.spbill_create_ip  客户端外网ip
     * @param callback
     */
    private void prepay(Map<String, String> params,String url, final WXPayCallback callback)
    {
        int totalFee = 0;
        //下面代码需要改
//        String token = (String) PreferenceUtils.get("token", "1");
//        params.put("token", token);

        params.put("body", params.get("body"));
        params.put("total_fee", params.get("total_fee"));
        params.put("spbill_create_ip", params.get("spbill_create_ip"));

        httpManager.doPost(url, params,new OkHttpManager.ResultCallback<BaseResp>()
        {
            @Override
            public void onError(String simpleMsg, Exception e)
            {
                callback.onFailed(simpleMsg);
            }

            @Override
            public void onSuccess(BaseResp response)
            {
                MapInfoBean mi = response.mapInfo;
                if(mi != null)
                {
                    WXPayResp wr = mi.getWxpayResp();
                    if(!wr.getResult_code().equals("FAIL"))
                    {
                        genPayReq(wr, callback);
                    }else
                    {
                        callback.onFailed(wr.getResult_msg());
                    }
                } else
                {
                    callback.onFailed("预支付订单为空");
                    return;
                }
            }
        });
    }

//    private Map<String, String> resultunifiedorder;
//    private StringBuffer sb;

    /***
     * 发起支付
     */
    private void genPayReq(WXPayResp wr, WXPayCallback callback)
    {
        PayReq req = new PayReq();
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
        req.appId = wr.getAppid();
        req.partnerId = wr.getMch_id();
        req.prepayId = wr.getPrepay_id();
        req.packageValue = "Sign=WXPay";
        req.nonceStr = wr.getNonce_str();
        req.timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        req.sign = wr.getSign();
        msgApi.registerApp(wr.getAppid());
        msgApi.sendReq(req);
        callback.onSuccess("成功");
    }

    /***
     * 解析微信返回的xml
     * @param content
     * @return
     */
//    public Map<String, String> decodeXml(String content)
//    {
//        try
//        {
//            Map<String, String> xml = new HashMap<>();
//            XmlPullParser parser = Xml.newPullParser();
//            parser.setInput(new StringReader(content));
//            int event = parser.getEventType();
//            while (event != XmlPullParser.END_DOCUMENT)
//            {
//                String nodeName = parser.getName();
//                switch (event)
//                {
//                    case XmlPullParser.START_DOCUMENT:
//                        break;
//                    case XmlPullParser.START_TAG:
//                        if ("xml".equals(nodeName) == false)
//                        {
//                            xml.put(nodeName, parser.nextText());
//                        }
//                        break;
//                    case XmlPullParser.END_TAG:
//                        break;
//                }
//                event = parser.next();
//            }
//            return xml;
//        } catch (Exception e)
//        {
//        }
//        return null;
//
//    }

    /***
     * 生成一个随机串
     * @return
     */
//    private String genNonceStr()
//    {
//        Random random = new Random();
//        return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
//    }

    /***
     * 获得时间戳
     * @return
     */
    private long genTimeStamp()
    {
        return System.currentTimeMillis() / 1000;
    }

    /***
     * 获得外网IP
     * @return
     */
    public String GetNetIp()
    {
        URL infoUrl = null;
        InputStream inStream = null;
        try
        {
            infoUrl = new URL("http://1212.ip138.com/ic.asp");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK)
            {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inStream, "gb2312"));
                StringBuffer strber = new StringBuffer();
                String line = null;
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();

                int start = strber.indexOf("[") + 1;
                int end = strber.lastIndexOf("]");

                line = strber.substring(start, end);
                Message msg = handler.obtainMessage();
                msg.obj = line;
                msg.what = 1;
                handler.sendMessage(msg);
                return line;
            } else
            {
                handler.sendEmptyMessage(0);
            }
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        } catch (IOException e)
        {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
        return null;
    }

    /**
     * 生成签名
     */
//    private String genPackageSign(List<NameValuePair> params)
//    {
//        StringBuilder sb = new StringBuilder();
//
//        for (int i = 0; i < params.size(); i++)
//        {
//            sb.append(params.get(i).getName());
//            sb.append('=');
//            sb.append(params.get(i).getValue());
//            sb.append('&');
//        }
//        sb.append("key=");
//        //API_KEY替换为应用申请的
//        sb.append("APP_KEY");
//
//        String packageSign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
//        return packageSign;
//    }

    /***
     * 微信发起支付
     * @param params <b>请求的参数 1.body 商品名称， 2.total_fee 总金额</b>
     * @param callback 微信回调
     */
    public void doPay(final Map<String, String> params, final String url, final WXPayCallback callback)
    {
        callback.onSatrt();

        new Thread()
        {
            @Override
            public void run()
            {
                GetNetIp();
            }
        }.start();

        handler = new Handler(Looper.getMainLooper())
        {
            @Override
            public void handleMessage(Message msg)
            {
                switch (msg.what)
                {
                    case 1:
                        String ip = (String) msg.obj;
                        params.put("spbill_create_ip", ip);
                        prepay(params,url, callback);
                        break;
                    case 0:
                        callback.onFailed("获取客户端ip失败");
                        break;
                    case 2:
                        break;
                }
            }
        };
    }

    public void login(WXAccessTokenCallback callback)
    {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat";
        api.sendReq(req);
        callback.onSatrt();
    }

    public interface WXPayCallback
    {
        public void onSatrt();

        public void onFailed(String msg);

        public void onSuccess(String msg);
    }

    public interface WXAccessTokenCallback
    {
        public void onSatrt();

        public void onFailed(String msg);

        public void onSuccess(String msg);
    }
}
